'use strict';

// 谷歌翻译
const puppeteer = require('puppeteer');

// toLang
// en
// vi 越南
// th 泰语
// hi 印地语
function fy(toLang, text) {
    text = encodeURIComponent(text);
    const baseUrl = `https://translate.google.com/?hl=zh-CN&sl=zh-CN&tl=${toLang}&text=${text}&op=translate`;
    return new Promise((resolve) => {
        (async () => {
            const browser = await puppeteer.launch();
            const page = await browser.newPage();
            await page.goto(baseUrl);
            await page.setViewport({width: 1080, height: 1024});
            const res = await page.evaluate(async () => {
                await new Promise((r) => setTimeout(r, 3000));
                let elems = document.querySelectorAll('.ryNqvb');
                const res = [];
                for (let i = 0; i < elems.length; i++) {
                    const elm = elems[i];
                    res.push(elm.innerText);
                }
                return res;
            });
            await browser.close();
            resolve(res);
        })();
    });
}

const args = process.argv;
const n = args.length;
if (n >= 3) {
    let toLang = 'en';
    let text;
    if (n === 3) {
        text = args[2];
    } else if (n === 4) {
        toLang = args[2];
        text = args[3];
    }
    if (text) {
        fy(toLang, text).then((res) => {
            console.log(JSON.stringify(res));
        });
    }
}
